package com.huishu.tcm.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huishu.tcm.entity.*;
import com.huishu.tcm.service.*;
import com.huishu.tcm.vo.PersonalCenterVo;
import com.huishu.tcm.vo.PrescriptionVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "糖尿病前期健康筛查、个性化管理方案、患者随访监测管理")
@RestController
@RequestMapping("/api/annex")
public class AnnexController {

    @Resource
    Annex1Service annex1Service;
    @Resource
    Annex2Service annex2Service;
    @Resource
    Annex4Service annex4Service;
    @Resource
    Annex5Service annex5Service;
    @Resource
    Annex6Service annex6Service;
    @Resource
    CustomizeService customizeService;

    // 查询糖尿病前期健康筛查录入历史记录
    @ApiOperation(value = "查询糖尿病前期健康筛查历史记录",
        notes = "返回值：{annex1:[...],annex2:[...],...}")
    @GetMapping(value = "/queryHistoryAnnex", params = {"patientId"})
    public Map<String,Object> queryHistoryAnnex(int patientId){
        Map<String, Object> map = new HashMap<>();
        
        QueryWrapper<Annex1> annex1QueryWrapper = new QueryWrapper<>();
        annex1QueryWrapper.eq("patient_id", patientId);
        List<Annex1> annex1List = annex1Service.list(annex1QueryWrapper);
        map.put("annex1", annex1List);

        QueryWrapper<Annex2> annex2QueryWrapper = new QueryWrapper<>();
        annex2QueryWrapper.eq("patient_id", patientId);
        List<Annex2> annex2List = annex2Service.list(annex2QueryWrapper);
        map.put("annex2", annex2List);

        QueryWrapper<Annex4> annex4QueryWrapper = new QueryWrapper<>();
        annex4QueryWrapper.eq("patient_id", patientId);
        List<Annex4> annex4List = annex4Service.list(annex4QueryWrapper);
        map.put("annex4", annex4List);

        QueryWrapper<Annex5> annex5QueryWrapper = new QueryWrapper<>();
        annex5QueryWrapper.eq("patient_id", patientId);
        List<Annex5> annex5List = annex5Service.list(annex5QueryWrapper);
        map.put("annex5", annex5List);

        QueryWrapper<Annex6> annex6QueryWrapper = new QueryWrapper<>();
        annex6QueryWrapper.eq("patient_id", patientId);
        List<Annex6> annex6List = annex6Service.list(annex6QueryWrapper);
        map.put("annex6", annex6List);

        QueryWrapper<Customize> customizeQueryWrapper = new QueryWrapper<>();
        customizeQueryWrapper.eq("patient_id", patientId);
        List<Customize> customizeList = customizeService.list(customizeQueryWrapper);
        map.put("customize", customizeList);
        return map;
    }


    @Resource
    PrescriptionHealthEducationService prescriptionHealthEducationService; // 健康教育
    @Resource
    PrescriptionDietService prescriptionDietService;// 膳食
    @Resource
    PrescriptionMotionService prescriptionMotionService; // 运动
    @Resource
    PrescriptionLoseWeightService prescriptionLoseWeightService; // 减重
    @Resource
    PrescriptionSleepService prescriptionSleepService;// 睡眠
    @Resource
    PrescriptionPhysiqueService prescriptionPhysiqueService; // 偏颇体质调理
    @Resource
    PrescriptionOtherService prescriptionOtherService;// 其他处方

    // 查询个性化健康管理方案录入历史数据
    @ApiOperation(value = "查询个性化健康管理方案历史数据",
        notes = "返回值：{健康教育healthEducation:[...],膳食diet:[...]," +
            "运动motion:[...],减重loseWeight:[...],睡眠sleep:[...],偏颇体质调理physique:[...],其他other:[...]}")
    @GetMapping(value = "/queryHistoryPrescription", params = {"patientId"})
    public Map<String,Object> queryHistoryPrescription(int patientId){
        Map<String, Object> map = new HashMap<>();

        QueryWrapper<PrescriptionHealthEducation> healthEducationQueryWrapperQueryWrapper = new QueryWrapper<>();
        healthEducationQueryWrapperQueryWrapper.eq("patient_id", patientId);
        List<PrescriptionHealthEducation> healthEducationList = prescriptionHealthEducationService.list(healthEducationQueryWrapperQueryWrapper);
        map.put("healthEducation", healthEducationList);

        QueryWrapper<PrescriptionDiet> dietQueryWrapper = new QueryWrapper<>();
        dietQueryWrapper.eq("patient_id", patientId);
        List<PrescriptionDiet> dietList = prescriptionDietService.list(dietQueryWrapper);
        map.put("diet", dietList);

        QueryWrapper<PrescriptionMotion> motionQueryWrapper = new QueryWrapper<>();
        motionQueryWrapper.eq("patient_id", patientId);
        List<PrescriptionMotion> motionList = prescriptionMotionService.list(motionQueryWrapper);
        map.put("motion", motionList);

        QueryWrapper<PrescriptionLoseWeight> loseWeightQueryWrapper = new QueryWrapper<>();
        loseWeightQueryWrapper.eq("patient_id", patientId);
        List<PrescriptionLoseWeight> loseWeightList = prescriptionLoseWeightService.list(loseWeightQueryWrapper);
        map.put("loseWeight", loseWeightList);

        QueryWrapper<PrescriptionSleep> sleepQueryWrapper = new QueryWrapper<>();
        sleepQueryWrapper.eq("patient_id", patientId);
        List<PrescriptionSleep> sleepList = prescriptionSleepService.list(sleepQueryWrapper);
        map.put("sleep", sleepList);

        QueryWrapper<PrescriptionPhysique> physiqueQueryWrapper = new QueryWrapper<>();
        physiqueQueryWrapper.eq("patient_id", patientId);
        List<PrescriptionPhysique> physiqueList = prescriptionPhysiqueService.list(physiqueQueryWrapper);
        map.put("physique", physiqueList);

        QueryWrapper<PrescriptionOther> otherQueryWrapper = new QueryWrapper<>();
        otherQueryWrapper.eq("patient_id", patientId);
        List<PrescriptionOther> otherList = prescriptionOtherService.list(otherQueryWrapper);
        map.put("other", otherList);
        return map;
    }



    @Resource
    Annex7Service annex7Service;

    @ApiOperation(value = "查询中医健康管理随访监测记录表历史数据")
    @GetMapping(value = "/queryHistoryAnnex7", params = {"patientId"})
    public List<Annex7> queryHistoryAnnex7(int patientId){
        QueryWrapper<Annex7> annex7QueryWrapper = new QueryWrapper<>();
        annex7QueryWrapper.eq("patient_id", patientId);
        return annex7Service.list(annex7QueryWrapper);
    }


    @Resource
    UserService userService;

    @ApiOperation(value = "根据社区医疗机构id查询未完成的用户列表", notes = "根据社区医疗机构id查询未完成的用户列表")
    @GetMapping(value = "/queryToBeContinued", params = {"institutionId"})
    public List<User> queryToBeContinued(int institutionId){
        List<User> result = new ArrayList<>();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("institution_id", institutionId);
        List<User> userList = userService.list(userQueryWrapper);
        for(User user: userList){
            QueryWrapper<Annex1> annex1QueryWrapper = new QueryWrapper<>();
            annex1QueryWrapper.eq("patient_id", user.getId());
            List<Annex1> annex1List = annex1Service.list(annex1QueryWrapper);
            
            QueryWrapper<Annex2> annex2QueryWrapper = new QueryWrapper<>();
            annex2QueryWrapper.eq("patient_id", user.getId());
            List<Annex2> annex2List = annex2Service.list(annex2QueryWrapper);
            
            QueryWrapper<Annex4> annex4QueryWrapper = new QueryWrapper<>();
            annex4QueryWrapper.eq("patient_id", user.getId());
            List<Annex4> annex4List = annex4Service.list(annex4QueryWrapper);
            
            QueryWrapper<Annex5> annex5QueryWrapper = new QueryWrapper<>();
            annex5QueryWrapper.eq("patient_id", user.getId());
            List<Annex5> annex5List = annex5Service.list(annex5QueryWrapper);
            
            QueryWrapper<Annex6> annex6QueryWrapper = new QueryWrapper<>();
            annex6QueryWrapper.eq("patient_id", user.getId());
            List<Annex6> annex6List = annex6Service.list(annex6QueryWrapper);
            
            QueryWrapper<Customize> customizeQueryWrapper = new QueryWrapper<>();
            customizeQueryWrapper.eq("patient_id", user.getId());
            List<Customize> customizeList = customizeService.list(customizeQueryWrapper);
            
            QueryWrapper<Annex7> annex7QueryWrapper = new QueryWrapper<>();
            annex7QueryWrapper.eq("patient_id", user.getId());
            List<Annex7> annex7List = annex7Service.list(annex7QueryWrapper);
            if(ObjectUtil.isEmpty(annex1List) && ObjectUtil.isEmpty(annex2List) && ObjectUtil.isEmpty(annex4List) &&
                ObjectUtil.isEmpty(annex5List) && ObjectUtil.isEmpty(annex6List) && ObjectUtil.isEmpty(customizeList) &&
                ObjectUtil.isEmpty(annex7List)){
                result.add(user);
            }
        }
        return result;
    }

    @ApiOperation(value = "根据社区医疗机构id查询已完成的用户列表", notes = "根据社区医疗机构id查询已完成的用户列表")
    @GetMapping(value = "/queryCompleted", params = {"institutionId"})
    public List<User> queryCompleted(int institutionId){
        List<User> result = new ArrayList<>();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("institution_id", institutionId);
        List<User> userList = userService.list(userQueryWrapper);
        for(User user: userList){
            QueryWrapper<Annex7> annex7QueryWrapper = new QueryWrapper<>();
            annex7QueryWrapper.eq("patient_id", user.getId());
            List<Annex7> annex7List = annex7Service.list(annex7QueryWrapper);
            if(ObjectUtil.isNotEmpty(annex7List)){
                result.add(user);
            }
        }
        return result;
    }


    @Resource
    ComparativeService comparativeService;

    // 个人中心数据
    @ApiOperation(value = "根据社区医疗机构id查询个人中心数据", notes = "根据社区医疗机构id查询个人中心数据")
    @GetMapping(value = "/queryPersonalCenterData", params = {"institutionId"})
    public PersonalCenterVo queryPersonalCenterData(int institutionId){
        PersonalCenterVo personalCenterVo = new PersonalCenterVo();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("institution_id", institutionId);
        List<User> userList = userService.list(userQueryWrapper);
        personalCenterVo.setManagementTeamCount(userList.size());
        personalCenterVo.setManagementTeamEndManagementCount(userList.stream().filter((item)->item.getEndManagement() == true).toArray().length);
        personalCenterVo.setManagementTeamInManagementCount(personalCenterVo.getManagementTeamCount() - personalCenterVo.getManagementTeamEndManagementCount());
        personalCenterVo.setManagementTeamUnCompletedCount(queryToBeContinued(institutionId).size());
        personalCenterVo.setManagementTeamCompletedCount(queryCompleted(institutionId).size());

        QueryWrapper<Comparative> comparativeQueryWrapper = new QueryWrapper<>();
        comparativeQueryWrapper.eq("institution_id", institutionId);
        List<Comparative> comparativeList = comparativeService.list(comparativeQueryWrapper);
        personalCenterVo.setComparativeTeamCount(comparativeList.size());
        personalCenterVo.setComparativeTeamEarlyCount(comparativeList.stream().filter((item) -> item.getRole().equals("0")).toArray().length);
        personalCenterVo.setComparativeTeamDiabetesCount(personalCenterVo.getComparativeTeamCount() - personalCenterVo.getComparativeTeamEarlyCount());
        return personalCenterVo;
    }


    @ApiOperation(value = "开具处方", notes = "开具处方")
    @PostMapping("/savePrescription")
    public void savePrescription(@RequestBody PrescriptionVo prescriptionVo){
        // 保存健康教育处方
        PrescriptionHealthEducation prescriptionHealthEducation = prescriptionVo.getPrescriptionHealthEducation();
        QueryWrapper<PrescriptionHealthEducation> healthEducationQueryWrapper = new QueryWrapper<>();
        healthEducationQueryWrapper.eq("patient_id",prescriptionHealthEducation.getPatientId());
        healthEducationQueryWrapper.orderByDesc("number");
        List<PrescriptionHealthEducation> healthEducationList = prescriptionHealthEducationService.list(healthEducationQueryWrapper);
        if(ObjectUtil.isEmpty(healthEducationList)){
            prescriptionHealthEducation.setNumber(1);
        }else{
            prescriptionHealthEducation.setNumber(healthEducationList.get(0).getNumber() + 1);
        }
        prescriptionHealthEducationService.save(prescriptionHealthEducation);

        // 保存膳食处方
        PrescriptionDiet prescriptionDiet = prescriptionVo.getPrescriptionDiet();
        QueryWrapper<PrescriptionDiet> dietQueryWrapper = new QueryWrapper<>();
        dietQueryWrapper.eq("patient_id",prescriptionDiet.getPatientId());
        dietQueryWrapper.orderByDesc("number");
        List<PrescriptionDiet> prescriptionDietList = prescriptionDietService.list(dietQueryWrapper);
        if(ObjectUtil.isEmpty(prescriptionDietList)){
            prescriptionDiet.setNumber(1);
        }else{
            prescriptionDiet.setNumber(prescriptionDietList.get(0).getNumber() + 1);
        }
        prescriptionDietService.save(prescriptionDiet);

        // 保存减重处方
        PrescriptionLoseWeight prescriptionLoseWeight = prescriptionVo.getPrescriptionLoseWeight();
        QueryWrapper<PrescriptionLoseWeight> loseWeightQueryWrapper = new QueryWrapper<>();
        loseWeightQueryWrapper.eq("patient_id",prescriptionLoseWeight.getPatientId());
        loseWeightQueryWrapper.orderByDesc("number");
        List<PrescriptionLoseWeight> loseWeightList = prescriptionLoseWeightService.list(loseWeightQueryWrapper);
        if(ObjectUtil.isEmpty(loseWeightList)){
            prescriptionLoseWeight.setNumber(1);
        }else{
            prescriptionLoseWeight.setNumber(loseWeightList.get(0).getNumber() + 1);
        }
        prescriptionLoseWeightService.save(prescriptionLoseWeight);

        // 保存运动处方
        PrescriptionMotion prescriptionMotion = prescriptionVo.getPrescriptionMotion();
        QueryWrapper<PrescriptionMotion> prescriptionMotionQueryWrapper = new QueryWrapper<>();
        prescriptionMotionQueryWrapper.eq("patient_id",prescriptionLoseWeight.getPatientId());
        prescriptionMotionQueryWrapper.orderByDesc("number");
        List<PrescriptionMotion> motionList = prescriptionMotionService.list(prescriptionMotionQueryWrapper);
        if(ObjectUtil.isEmpty(motionList)){
            prescriptionMotion.setNumber(1);
        }else{
            prescriptionMotion.setNumber(motionList.get(0).getNumber() + 1);
        }
        prescriptionMotionService.save(prescriptionMotion);

        //保存其他处方
        PrescriptionOther prescriptionOther = prescriptionVo.getPrescriptionOther();
        QueryWrapper<PrescriptionOther> otherQueryWrapper = new QueryWrapper<>();
        otherQueryWrapper.eq("patient_id",prescriptionLoseWeight.getPatientId());
        otherQueryWrapper.orderByDesc("number");
        List<PrescriptionOther> otherList = prescriptionOtherService.list(otherQueryWrapper);
        if(ObjectUtil.isEmpty(otherList)){
            prescriptionOther.setNumber(1);
        }else{
            prescriptionOther.setNumber(otherList.get(0).getNumber() + 1);
        }
        prescriptionOtherService.save(prescriptionOther);

        // 保存体质改善处方
        PrescriptionPhysique prescriptionPhysique = prescriptionVo.getPrescriptionPhysique();
        QueryWrapper<PrescriptionPhysique> physiqueQueryWrapper = new QueryWrapper<>();
        physiqueQueryWrapper.eq("patient_id",prescriptionLoseWeight.getPatientId());
        physiqueQueryWrapper.orderByDesc("number");
        List<PrescriptionPhysique> physiqueList = prescriptionPhysiqueService.list(physiqueQueryWrapper);
        if(ObjectUtil.isEmpty(physiqueList)){
            prescriptionPhysique.setNumber(1);
        }else{
            prescriptionPhysique.setNumber(physiqueList.get(0).getNumber() + 1);
        }
        prescriptionPhysiqueService.save(prescriptionPhysique);

        // 保存睡眠管理处方
        PrescriptionSleep prescriptionSleep = prescriptionVo.getPrescriptionSleep();
        QueryWrapper<PrescriptionSleep> sleepQueryWrapper = new QueryWrapper<>();
        sleepQueryWrapper.eq("patient_id",prescriptionLoseWeight.getPatientId());
        sleepQueryWrapper.orderByDesc("number");
        List<PrescriptionSleep> sleepList = prescriptionSleepService.list(sleepQueryWrapper);
        if(ObjectUtil.isEmpty(sleepList)){
            prescriptionSleep.setNumber(1);
        }else{
            prescriptionSleep.setNumber(sleepList.get(0).getNumber() + 1);
        }
        prescriptionSleepService.save(prescriptionSleep);
    }
}
